package com.demo.petshop.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.*;
import org.springframework.stereotype.Component;

@Component
public class ZhipuAiUtil {
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    @Value("${zhipu.api-key}")
    private String apiKey;

    public  String chatWithZhipu(String question) {
        WebClient client = WebClient.create(API_URL);

        Map<String, Object> message = Map.of(
                "role", "user",
                "content", question
        );
        Map<String, Object> body = Map.of(
                "model", "glm-4", // 你也可以用 glm-3-turbo
                "messages", List.of(message)
        );

        Mono<Map<String, Object>> responseMono = client.post()
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(body)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {}); // 修改这里

        Map<String, Object> response = responseMono.block();
        if (response != null && response.containsKey("choices")) {
            List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
            if (!choices.isEmpty()) {
                Map<String, Object> choice = choices.get(0);
                Map<String, Object> msg = (Map<String, Object>) choice.get("message");
                return (String) msg.get("content");
            }
        }
        return "AI服务暂时不可用";
    }
}
